<?php
class PublicAction extends AdminAction
{
	/**
	 * 登录
	 */
	public function login()
	{
		if(isset($_POST['dosubmit'])) {
			$this->assign("jumpUrl", U('public/login'));
			if (empty($_POST['login_name'])) {
				$this->error('管理员帐号必须填写！');
			}
			if (empty($_POST['login_pwd'])) {
				$this->error('管理员密码必须填写！');
			}
			//if(strtolower($_SESSION['vcode']) != trim(strtolower($_POST['vcode']))) {
	  		//$this->error('验证码错误,请重新输入！');
	  	//}
	    $where = array();
			$where['username'] = trim($_POST['login_name']);
			$where['admin.display'] = 1;
			$rs  = M("admin");
			$list= $rs->field('admin.*,admin_role.rolename')->join('admin_role ON admin_role.id = roleid')->where($where)->find();

	    //使用用户名、密码和状态的方式进行认证
	    if (false == $list) {
	    	$this->error('管理员帐号不存在！');
	    }
			if ($list['password'] != md5(trim($_POST['login_pwd']))) {
				$this->error('用户密码错误,请重新输入！');
			}
			// 缓存访问权限
			$_SESSION['admin_user_info'] = array(
				'id' => $list['id'],
				'user_name' => $list['username'],
				'roleid' => $list['roleid'],
				'role_name' => $list['rolename'] ? $list['rolename'] : ($list['roleid']==1 ? '超级管理员' : '不明身份'),
			);
			//保存登陆信息
			$data = array();
			$data['id']         = $list['id'];
			$data['lastloginip']    = get_client_ip();
			$data['lastlogintime']  = time();
			$rs->save($data);
			redirect(U('Index/Index'));
		}
		$this->display('login');
	}
		
	/**
	 * 登出
	 */
	public function logout()
	{
		unset($_SESSION['admin_user_info']);
		$this->display('login');
	}
	
/**
	 * 左侧菜单
	 * @param int $menuid 顶级菜单ID号
	 */
	public function menu_left()
	{
		$menuid = intval($_GET['menuid']);
		$datas = $this->menu($menuid);
		if (isset($_GET['parentid']) && $parentid = intval($_GET['parentid']) ? intval($_GET['parentid']) : 1) {
			foreach($datas as $_value) {
	        	if($parentid==$_value['id']) {
	        		echo '<li id="_M'.$_value['id'].'" class="on top_menu"><a href="javascript:_M('.$_value['id'].',\''.U($value['c'].'/'.$value['a']).'\')" hidefocus="true" style="outline:none;">'.$_value['name'].'</a></li>';
	        		
	        	} else {
	        		echo '<li id="_M'.$_value['id'].'" class="top_menu"><a href="javascript:_M('.$_value['id'].',\''.U($value['c'].'/'.$value['a']).'\')"  hidefocus="true" style="outline:none;">'.$_value['name'].'</a></li>';
	        	}      	
	        }
		} else {
			$leftmenu = '';
			if(isset($datas) && $datas){
				foreach($datas as $_value) {
					$leftmenu .= '<h3 class="f14"><span class="switchs cu on" title="展开与收缩"></span>'.$_value['name'].'</h3>';
					$leftmenu .=  '<ul>';
					$sub_array = $this->menu($_value['id']);
					if($sub_array){
						foreach($sub_array as $_key=>$_m) {
							//附加参数
							$data = $_m['data'] ? '&'.$_m['data'] : '';
							if($menuid == 5) { //左侧菜单不显示选中状态
								$classname = 'class="sub_menu"';
							} else {
								$classname = 'class="sub_menu"';
							}
							$leftmenu .=  '<li id="_MP'.$_m['id'].'" '.$classname.'><a href="javascript:_MP('.$_m['id'].',\''.U('Admin/'.$_m['c'].'/'.$_m['a'], $data).'\');" hidefocus="true" style="outline:none;">'.$_m['name'].'</a></li>';
						}
					}
					$leftmenu .=  '</ul>';
				}
			}
			$this->assign('leftmenu', $leftmenu);
			$this->display('left');
		}
	}
	
	/**
	 * 后台首页
	 */
	public function main()
	{
		//登录信息
		$admindb = D('admin');
		$admin_info = $admindb->field('lastlogintime,lastloginip')->where('id=' . $_SESSION['admin_user_info']['id'])->find();
		//用户角色
		$roledb = D('admin_role');
		$role_info = $roledb->getField('rolename', 'id=' . $_SESSION['admin_user_info']['roleid']);
		$admin_info['rolename'] = $role_info;
		$this->assign('user', $admin_info);
		//快捷方式
		$paneldb = D('admin_panel');
		$adminpanel = $paneldb->where(array('userid'=>$_SESSION['admin_user_info']['id']))->order('datetime DESC')->select();
		$this->assign('adminpanel', $adminpanel);
		
		/**********订单统计信息***********/
		$order_db = D('orders');
		//待发货订单数量
		$orderStatistics['unshipping_count'] = $order_db->where(array('order_status' => OrderModel::ORDER_CONFIRMED, 'payment_status' => OrderModel::PAY_PAYED, 'shipping_status' => OrderModel::SHIPPING_UNSHIPPED))->count();
		//部分发货订单数量
		$orderStatistics['part_shipping_count'] = $order_db->where(array('order_status' => OrderModel::ORDER_CONFIRMED, 'payment_status' => OrderModel::PAY_PAYED, 'shipping_status' => OrderModel::SHIPPING_SHIPPED_PART))->count();
		//未确认订单数
		$orderStatistics['unconfirm_count'] = $order_db->where(array('order_status' => OrderModel::ORDER_UNCONFIRMED))->count();
		//待支付订单数
		$orderStatistics['unpay_count'] = $order_db->where(array('order_status' => OrderModel::ORDER_CONFIRMED, 'payment_status' => OrderModel::PAY_UNPAYED))->count();
		//已完成订单数
		$orderStatistics['comlite_count'] = $order_db->where(array('order_status' => OrderModel::ORDER_COMPLETE))->count();
		$this->assign('orderStatistics', $orderStatistics);
		
		/**************商品统计信息*******************/
		$product_db = D('product');
		$category_product_db = D('category_product');
		$productStatistics['product_count'] = $product_db->count();
		$productStatistics['warming_count'] = $product_db->where(array('display' => 1, 'stock' => array('lt',2)))->count();
		//推荐分类
		$topCategoryList = CategoryModel::getCategoryListBase(CategoryModel::TYPE_RECOMMEND);
		if($topCategoryList){
			foreach ($topCategoryList as &$cat){
				$cat['count'] = $category_product_db->where('catid='.$cat['id'])->count();
			}
		}
		$productStatistics['topCategoryList'] = $topCategoryList;
		$this->assign('productStatistics', $productStatistics);
		
		$this->display('main');
	}
	
	/**
	 * 当前位置
	 */
	public function public_current_pos()
	{
		echo $this->current_pos($_GET['menuid']);
		exit;
	}
	
	/**
	 * ajax添加快捷方式
	 */
	public function ajax_add_panel()
	{
		$menuid = isset($_POST['menuid']) ? $_POST['menuid'] : exit('0');
		$menudb = D('menu');
		$menuarr = $menudb->where(array('id'=>$menuid))->find();
		$url = U('admin/'.$menuarr['c'].'/'.$menuarr['a'],$menuarr['data']);
		$data = array('menuid'=>$menuid, 'userid'=>$_SESSION['admin_user_id'], 'name'=>$menuarr['name'], 'url'=>$url, 'datetime'=>time());
		$paneldb = D('admin_panel');
		$paneldb->add($data);
		$panelarr = $paneldb->where(array('userid'=>$_SESSION['admin_user_id']))->order('datetime DESC')->select();
		foreach($panelarr as $v) {
			echo "<span><a onclick='paneladdclass(this);' target='right' href='".U($v['url'],'menuid='.$v['menuid'])."'>".$v['name']."</a>  <a class='panel-delete' href='javascript:delete_panel(".$v['menuid'].");'></a></span>";
		}
		exit;
	}
	
	/**
	 * ajax删除快捷方式
	 */
	public function ajax_delete_panel()
	{
		$menuid = isset($_POST['menuid']) ? $_POST['menuid'] : exit('0');
		$paneldb = D('admin_panel');
		$paneldb->where(array('menuid'=>$menuid, 'userid'=>$_SESSION['admin_user_id']))->delete();
		$panelarr = $paneldb->where(array('userid'=>$_SESSION['admin_user_id']))->order('datetime DESC')->select();
		foreach($panelarr as $v) {
			echo "<span><a onclick='paneladdclass(this);' target='right' href='".U($v['url'],'menuid='.$v['menuid'])."'>".$v['name']."</a>  <a class='panel-delete' href='javascript:delete_panel(".$v['menuid'].");'></a></span>";
		}
		exit;
	}
	
	/**
	 * 清空缓存
	 */
	public function clear_cache()
	{
		import('COM.Dir');
		$dir = new Dir();
		$dir->delDir(DATA_PATH);
		$dir->delDir(CACHE_PATH);
		$dir->delDir(LOG_PATH);
		$dir->delDir(TEMP_PATH);
		@unlink(APP_PATH.'Runtime/~runtime.php');
		@unlink(ROOT_PATH.'/'.WEB_APP_NAME.'/Runtime/~runtime.php');
		redirect(U('Index/Index'));
	}
	
	/**
	 * 验证码
	 */
	public function vcode()
	{
		import("COM.CheckCode");
    	$checkcode = new CheckCode();
    	if (isset($_GET['code_len']) && intval($_GET['code_len'])) $checkcode->code_len = intval($_GET['code_len']);
			if ($checkcode->code_len > 8 || $checkcode->code_len < 2) {
				$checkcode->code_len = 4;
			}
			if (isset($_GET['font_size']) && intval($_GET['font_size'])) $checkcode->font_size = intval($_GET['font_size']);
			if (isset($_GET['width']) && intval($_GET['width'])) $checkcode->width = intval($_GET['width']);
			if ($checkcode->width <= 0) {
				$checkcode->width = 130;
			}
			if (isset($_GET['height']) && intval($_GET['height'])) $checkcode->height = intval($_GET['height']);
			if ($checkcode->height <= 0) {
				$checkcode->height = 50;
			}
			if (isset($_GET['font_color']) && trim(urldecode($_GET['font_color'])) && preg_match('/(^#[a-z0-9]{6}$)/im', trim(urldecode($_GET['font_color'])))) $checkcode->font_color = trim(urldecode($_GET['font_color']));
			if (isset($_GET['background']) && trim(urldecode($_GET['background'])) && preg_match('/(^#[a-z0-9]{6}$)/im', trim(urldecode($_GET['background'])))) $checkcode->background = trim(urldecode($_GET['background']));
			$checkcode->doimage();
			$_SESSION['vcode'] = $checkcode->get_code();
    }
    
    /**
     * 条形码
     */
    public function barcode()
    {
    	$text = trim($_GET['text']);
    	if(empty($text)){exit;}
    	
    	import('COM.BarCode');
			echo BarCode::getBarCode($text);
    }
}
